using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
namespace TciNewsReader_2014_04.Infrastructure
{
    public class SingleInstanceAssembly
    {
        private readonly string _mutexName;
        private readonly Mutex _mutex;
        public bool IsUniqueInstance { get; private set; }
        private bool _createdNew;
        public SingleInstanceAssembly(Application application, out Mutex mutex)
        {
            _mutexName = application.GetType().Namespace;
            _mutex = mutex = new Mutex(true, _mutexName, out _createdNew);
            IsUniqueInstance = _createdNew;
        }
        public Mutex xStart()
        {
            // overloaded mutex constructor which outs a boolean
            // telling if the mutex is new or not.
            // see http://msdn.microsoft.com/en-us/library/System.Threading.Mutex.aspx
            // ReSharper disable once UnusedVariable
            var mutex = new Mutex(true, _mutexName, out _createdNew);
            IsUniqueInstance = _createdNew;
            return mutex;
        }
        public void CloseOtherInstance()
        {
            string myName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
            List<Process> processes = Process
                .GetProcesses()
                .Where(q => Path.GetFileNameWithoutExtension(q.ProcessName) == myName)
                .OrderBy(q => q.StartTime)
                .ToList();
            if (processes.Count >= 2)
            {
                //NativeMethods.FlashWindow(processes[0].MainWindowHandle.ToInt32());
                //NativeMethods.ShowWindow(processes[0].MainWindowHandle.ToInt32(), NativeMethods.SwRestore);
                //NativeMethods.SetForegroundWindow(processes[0].MainWindowHandle.ToInt32());
            }
            Console.Beep();
            Application.Current.Shutdown(0);
        }
    }
}